import React, { useEffect, useState } from 'react'
import { Button, Popconfirm, Table } from 'antd'
import ProjectForm from './form'

function Index(props) {
  const [tableData, setTableData] = useState([])

  async function getData() {
    let res = await window.electron.ipcRenderer.invoke('project-list')
    setTableData(res)
  }

  useEffect(() => {
    getData()
  }, [])

  const [visible, setVisible] = useState(false)
  const [current, setCurrent] = useState({ id: null, name: '' })

  function add() {
    setVisible(true)
    setCurrent({
      id: null,
      name: ''
    })
  }

  function edit(record) {
    setVisible(true)
    setCurrent(record)
  }

  async function save(data) {
    await window.electron.ipcRenderer.invoke(`project-${data.id ? 'edit' : 'add'}`, data)
    setVisible(false)
    await getData()
  }

  async function remove(record) {
    console.log(record)
    await window.electron.ipcRenderer.invoke('project-delete', { id: record.id })
    await getData()
  }

  const columns = [
    {
      title: '项目',
      dataIndex: 'name',
      key: 'name',
      width: 300
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <div>
            <Button type="link" onClick={() => {
              edit(record)
            }}>编辑</Button>
            <Popconfirm
              title="确认删除吗?"
              onConfirm={() => {
                remove(record)
              }}
              okText="Yes"
              cancelText="No"
            >
              <Button type="link" danger>删除</Button></Popconfirm>
          </div>
        )
      }
    }
  ]


  return (
    <div>
      <div className={'flex justify-end mb-4'}>
        <Button onClick={add} type={'primary'}>新建</Button>
      </div>
      <Table columns={columns} dataSource={tableData} bordered rowKey={'id'} />
      <ProjectForm visible={visible} project={current} onCancel={() => {
        setVisible(false)
      }} onSave={save}></ProjectForm>
    </div>
  )
}

export default Index
